# -*- coding:utf-8 -*-

from flask import render_template, redirect, request, url_for, flash, jsonify, session
from flask_login import login_required
from app import db
from app.models.account import Staff, DefPassword as DP
from app.tools.permission import permission
from app.tools.log import log
from app.tools.safe import safe_data
import datetime
from . import org


roles = {'service': u'客服部', 'review': u'车辆审批部', 'manage': u'综合管理部',
	'finance': u'财务部', 'hr': u'人资行政部', 'admin': u'管理层'}


@org.before_request
@login_required
@permission(['hr', 'admin', 'super'])
def check_permission():	#检查账户权限
	return

@org.route('/list/')
def org_list():	#返回组织架构的页面，相关的数据由ajax异步获取
	return render_template('account/org/org.html', title=u"组织架构")

@org.route('/get_list/<department>/')
def get_list(department):	#返回部门的人员，department指部门名称
	limit = int(request.values.get('limit', '10'))
	offset = int(request.values.get('offset', '0'))
	if department not in roles:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	staff = Staff.query.filter_by(role=department).order_by(db.desc(Staff.created)).paginate(offset/limit+1, limit, False)
	count = staff.total
	data = []
	for item in staff.items:
		data.append({
			'staff_number': item.staff_number,
			'phone': item.phone,
			'name': item.name,
			'state': u'启用' if item.account_state == 0 else u'禁用',
			'created': item.created.strftime("%Y-%m-%d %H:%M:%S"),
			'role': item.role,
			'operate': item.account_state
		})
	json = {'total': count, 'rows': data}
	return jsonify(json)

@org.route('/add_staff/', methods=["GET", "POST"])
def add_staff():					#添加新员工
	values = request.values
	data = {}
	data['staff_number'] = values.get('staff_number')
	data['name'] = values.get('name')
	data['phone'] = values.get('phone')
	data['role'] = values.get('department')
	for item in data.values():
		if not item:
			return jsonify({'state': -1, 'msg': u'参数不全'})
	count = Staff.query.filter_by(staff_number=data['staff_number']).count()
	if count != 0:	#检查该工号是否已经存在
		return jsonify({'state': 2, 'msg': u'工号已存在'})
	count = Staff.query.filter_by(phone=data['phone']).count()
	if count != 0:	#检查该手机号是否已经存在
		return jsonify({'state': 2, 'msg': u'手机号已存在'})
	pw = DP.query.first()
	data['password'] = pw.default_password if pw else '123456'	#设置密码
	data['account_state'] = 0
	data['created'] = datetime.datetime.now()
	data = safe_data(data)
	staff = Staff(**data)		
	staff.save()
	log(u'添加员工 %s'%staff.staff_number)
	return jsonify({'state': 0})

@org.route('/edit_staff/', methods=["GET", "POST"])
def edit_staff():					#修改员工信息
	values = request.values
	data = {}
	data['staff_number'] = values.get('staff_number')
	data['name'] = values.get('name')
	data['phone'] = values.get('phone')
	data['role'] = values.get('department')
	old_number = values.get('old_number')	#旧的工号
	if old_number is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if staff_number is None or name is None or phone is None or role is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	staff = Staff.query.filter_by(staff_number=old_number).first()
	if not staff:	#旧工号不存在
		return jsonify({'state': 3, 'msg': u'对象不存在'})
	if old_number != staff_number:	#修改工号
		count = Staff.query.filter_by(staff_number=staff_number).count()
		if count != 0:	#检查新工号是否已经存在
			return jsonify({'state': 4, 'msg': u'工号已经存在'})
	if phone != staff.phone:
		count = Staff.query.filter_by(phone=phone).count()
		if count != 0:	#检查新手机号是否已经存在
			return jsonify({'state': 2, 'msg': u'手机号已存在'})
	data['created'] = datetime.datetime.now()
	data = safe_data(data)
	staff.upgrade(data)
	db.session.commit()
	log(u'编辑员工 %s'%staff.staff_number)
	return jsonify({'state': 0})

@org.route('/reset/', methods=["GET", "POST"])
def reset():						#重置密码
	staff_number = request.values.get('staff_number')
	if staff_number is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	staff = Staff.query.filter_by(staff_number=staff_number).first()
	if not staff:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	pw = DP.query.first()
	staff.password = pw.default_password if pw else '123456'
	staff.save()
	log(u'重置员工%s密码'%staff.staff_number)
	return jsonify({'state': 0})

@org.route('/reverse/', methods=["GET", "POST"])
def reverse():						#反置账号状态
	staff_number = request.values.get('staff_number')
	if staff_number is None:
		return jsonify({'state': -1})
	staff = Staff.query.filter_by(staff_number=staff_number).first()
	if not staff:
		return jsonify({'state': 2})
	if staff.account_state == 0:
		staff.account_state = 1
	else:
		staff.account_state = 0
	staff.save()
	log(u'修改员工%s账户状态'%staff.staff_number)
	return jsonify({'state': 0})
